package com.bawei.park2302.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.bawei.lib_base.utils.utils.entity.ParkBean
import com.bawei.lib_base.utils.utils.entity.ParkBeanItem
import com.bawei.lib_base.utils.utils.res.Res
import com.bawei.lib_base.utils.utils.utils.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class ParkDataSource(val apiService : ApiService,val pare : String,val type : String) : PagingSource<Int,ParkBeanItem>(){
    override fun getRefreshKey(state: PagingState<Int, ParkBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkBeanItem> {
        return withContext(Dispatchers.IO){
            try {
                val page = params.key?:1
                val mutableListOf = mutableListOf<ParkBeanItem>()
                var bean : Res<ParkBean>?=null
                var bean2 : Res<ParkBeanItem>?=null
                if (type == "状态"){
                    bean = apiService.parkSpaceStatus(pare).first()
                    mutableListOf.addAll(bean.data)
                }else if (type == "类型"){
                    bean = apiService.parkSpaceType(pare).first()
                    mutableListOf.addAll(bean.data)
                }else if (type == "区域"){
                    bean = apiService.parkArea(pare.toInt()).first()
                    mutableListOf.addAll(bean.data)
                }else if (type == "车牌号"){
                    bean2 = apiService.parkLicensePlate(pare).first()
                    mutableListOf.add(bean2.data)
                }
                return@withContext LoadResult.Page(mutableListOf.sortedByDescending { it.id },null,null)
            }catch (e : Exception){
                return@withContext LoadResult.Error(e)
            }
        }
    }
}